import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Operation接口的动态代理处理器
 * 在方法调用前后添加日志记录功能
 */
public class OperationProxyHandler implements InvocationHandler {
    // 目标对象
    private Object target;

    // 日期格式化器
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 构造方法
    public OperationProxyHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 方法调用前的日志记录
        String timestamp = dateFormat.format(new Date());
        System.out.println("========================================");
        System.out.println("【日志记录 - 方法调用前】");
        System.out.println("时间: " + timestamp);
        System.out.println("目标对象: " + target.getClass().getName());
        System.out.println("方法名称: " + method.getName());
        System.out.println("方法参数: " + (args != null ? java.util.Arrays.toString(args) : "无参数"));
        System.out.println("========================================");

        // 记录方法调用开始时间
        long startTime = System.currentTimeMillis();

        // 调用目标对象的方法
        Object result = null;
        try {
            result = method.invoke(target, args);
        } catch (Exception e) {
            // 方法调用后的异常日志
            String endTimestamp = dateFormat.format(new Date());
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            System.out.println("========================================");
            System.out.println("【日志记录 - 方法调用后（异常）】");
            System.out.println("时间: " + endTimestamp);
            System.out.println("执行耗时: " + duration + " 毫秒");
            System.out.println("异常信息: " + e.getMessage());
            System.out.println("========================================");
            throw e;
        }

        // 方法调用后的日志记录
        String endTimestamp = dateFormat.format(new Date());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;

        System.out.println("========================================");
        System.out.println("【日志记录 - 方法调用后】");
        System.out.println("时间: " + endTimestamp);
        System.out.println("执行耗时: " + duration + " 毫秒");
        System.out.println("返回结果: " + (result != null ? result.toString() : "void"));
        System.out.println("执行状态: 成功");
        System.out.println("========================================");

        return result;
    }
}
